<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-button class="btn-add" type="primary" @click="addRoles()">添加角色</el-button>
      <!-- 角色列表区域 -->
      <el-table :data="roleslist" border style="width: 100%" stripe >
        <!-- 下拉框区域 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- {{scope.row.children}} -->
            <el-row :class="['bdbottom', 'vcenter',id === 0 ? 'bdtop' : '']" :gutter="30" v-for="(item, id) in scope.row.children" :key="id" align="center">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable  @close="removeTag(scope.row, id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级\三级权限 -->
              <el-col :span="18">
                <el-row :class="[sid === 0 ? '' : 'bdtop','vcenter']" v-for="(second , sid) in item.children" :key="sid">
                  <el-col :span="5">
                    <el-tag closable  @close="removeTag(scope.row, second.id)" type="success"> {{second.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="13">
                    <el-tag closable  @close="removeTag(scope.row, third.id)"  v-for="(third ,tid) in second.children" :key="tid" type="warning">{{third.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 角色信息区域 -->
        <el-table-column type="index" label="#" width="80" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"  align="center">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"  align="center">
        </el-table-column>
        <el-table-column label="操作" width="300px"  align="center">
          <template slot-scope="scope">
            <el-button type="primary" class="el-icon-edit" size="mini" @click="modifyRoles(scope.row)">编辑</el-button>
            <el-button type="warning" class="el-icon-delete" size="mini" @click="deleteRoles(scope.row.id)">删除
            </el-button>
            <el-button type="danger" class="el-icon-setting" size="mini" @click="setRights(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的窗口 -->
    <el-dialog title="添加角色" :visible.sync="dialogFormVisible" @close="resetForm()">
      <el-form :model="addRolesObj" :rules="rules" ref="addRolesObj">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesObj.roleName" clearable>12</el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesObj.roleDesc" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="submitAddRoles(addRolesObj)">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色的窗口 -->
    <el-dialog title="修改角色" :visible.sync="modifyFormVisible" @close="resetmodifyForm()">
      <el-form :model="modifyRolesObj" :rules="rules" ref="modifyRolesObj">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="modifyRolesObj.roleName" clearable>12</el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="modifyRolesObj.roleDesc" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="submitModifyRoles()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 询问是否确认删除窗口 -->
    <el-dialog title="删除权限" :visible.sync="deleVisible"   width="30%">
       <span>
         <i class="el-icon-info"></i>
         是否确认删除指定权限？
         </span>
       <span slot="footer" class="dialog-footer">
        <el-button @click="deleVisible=false">取 消</el-button>
        <el-button type="primary" @click="deteteTag()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 给角色分配权限的窗口 -->
    <el-dialog title="分配权限" :visible.sync="serRightsVisible"  width="50%" @closed="closeRights()">
      <el-tree :data="rightslist" :props="treeProps"   show-checkbox node-key="id" :default-checked-keys="defkeys" ref="treeRef">
      </el-tree>
       <span slot="footer" class="dialog-footer">
        <el-button @click="serRightsVisible=false">取 消</el-button>
        <el-button type="primary" @click="submitRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
export default {
  data () {
    return {
      //   角色列表
      roleslist: [],
      // 是否显示添加用户的窗口
      dialogFormVisible: false,
      // 表单数据验证
      rules: {
        roleName: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }]
      },
      // 添加用户窗口的数据
      addRolesObj: {
        roleName: '',
        roleDesc: ''
      },
      //   编辑用户窗口是否显示
      modifyFormVisible: false,
      modifyRolesObj: {
        roleName: '',
        roleDesc: ''
      },
      // 删除指定权限
      deleVisible: false,
      dpath: '',
      // 分配权限
      serRightsVisible: false,
      rightslist: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选择的节点id值的数组
      defkeys: [],
      // 用来修改权限的角色id
      roleid: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    //   1、获取数据，渲染到页面
    async getRolesList () {
      const {
        data: res
      } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.roleslist = res.data
    },
    //   添加角色按钮功能,点击显示添加组件
    addRoles () {
      this.dialogFormVisible = true
    },
    // 重置表单
    resetForm () {
      this.$refs.addRolesObj.resetFields()
    },
    //   新增角色功能
    async submitAddRoles (userdata) {
      // console.log(userdata)
      const {
        data: res
      } = await this.$http.post('roles', this.addRolesObj)
      // console.log(res)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      // 关闭添加角色窗口，将新增角色渲染到页面，弹出提示信息
      this.dialogFormVisible = false
      this.getRolesList()
      this.$message.success(res.meta.msg)
    },
    //   2、编辑角色功能
    async modifyRoles (userdata) {
      //   点击按钮将数据同步到表单中
      this.modifyFormVisible = true
      const {
        data: res
      } = await this.$http.get('roles/' + userdata.id)
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.modifyRolesObj = res.data
    },
    // 点击确定按钮，检查输入内容是否合法，通过检查就添加到后台数据库
    submitModifyRoles () {
      this.$refs.modifyRolesObj.validate(async valide => {
        if (!valide) return false
        // 将修改后数据提交到后台数据库
        const {
          data: res
        } = await this.$http.put('roles/' + this.modifyRolesObj.roleId, this.modifyRolesObj)
        if (res.meta.status !== 200) return this.$message.error('修改角色信息失败')
        //   关闭窗口，重新渲染窗口
        this.modifyFormVisible = false
        this.getRolesList()
        this.$message.success('修改角色信息成功！！！')
      })
    },
    // 重置表单  resetmodifyForm
    resetmodifyForm () {
      this.$refs.modifyRolesObj.resetFields()
    },
    // 删除用户按钮功能
    async deleteRoles (userid) {
      await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning',
        showCancelButton: true
      }).then(async () => {
        //   console.log(userid)
        const {
          data: res
        } = await this.$http.delete('roles/' + userid)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getRolesList()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 3、点击tag图标，移除指定权限
    removeTag (userdata, roleid) {
      // 点击删除，获取这条数据信息
      this.deleVisible = true
      this.dpath = 'roles/' + userdata.id + '/rights/' + roleid
      // console.log('角色id：' + userdata.id)
      // console.log('权限id：' + roleid)
    },
    // 确定删除
    async deteteTag () {
      // console.log(this.dpath)
      const { data: res } = await this.$http.delete(this.dpath)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('取消权限失败')
      //  关闭当前询问框，重新加载页面，显示提示信息
      this.deleVisible = false
      this.getRolesList()
      this.$message.success('删除成功')
    },
    // 4、给角色分配权限
    async setRights (userdata) {
      // this.serRightsVisible = true
      // console.log(userid)
      // 获取所有权限列表
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        this.serRightsVisible = false
        return this.$message.error('权限列表获取失败')
      }
      this.getLoafKeys(userdata, this.defkeys)
      this.serRightsVisible = true
      this.rightslist = res.data
      // 保存roleid给下面使用
      this.roleid = userdata.id
      // console.log(this.roleid)
    },
    // 通过递归形式获取三级权限的id
    getLoafKeys (node, arr) {
      // 如果当前节点不包含children属性，则是三级节点
      if (!node.children) return arr.push(node.id)
      node.children.forEach(element => {
        this.getLoafKeys(element, arr)
      })
    },
    // 关闭窗口事件,清空默认选择数组
    closeRights () {
      this.defkeys = []
    },
    // 提交勾选的权限，确定按钮事件
    async submitRights () {
    // 权限id列表：全选和半选中状态合在一起
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const idStr = keys.join(',')
      const path = 'roles/' + this.roleid + '/rights'
      const { data: res } = await this.$http.post(path, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      // 更新成功后重新渲染页面，关闭这个窗口
      this.getRolesList()
      this.serRightsVisible = false
      this.$message.success('更新成功')
    }
  }
}

</script>

<style lang="less" scoped>
  .el-breadcrumb {
    margin-bottom: 15px;
  }

  .btn-add {
    margin-bottom: 15px;
  }

  .el-tag {
    margin: 10px;
  }

  .bdtop {
    border-top: 1px dashed #ccc
  }

  .bdbottom {
    border-bottom: 1px dashed #ccc
  }

  // 垂直居中对齐
  .vcenter {
    display: flex;
    align-items: center;
  }
  .el-icon-info {
    color: rgb(241, 119, 119);
  }

</style>
